package com.example.demo.config;

import com.example.demo.common.AjaxResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import java.io.Serializable;

//通过这个类实现统一格式的返回，在数据返回给前端之前，检测数据的类型是否为统一的类型，如果不是，就封装为统一的对象
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice, Serializable {
    @Resource
    private ObjectMapper objectMapper;
    //确认调用beforebodywrite
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    @SneakyThrows
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //如果是我们规定的类型，就直接返回数据
        if (body instanceof AjaxResult) return body;
        //如果是字符串类型，我们就需要将它封装到对象中，然后将对象转换为json格式返回
        if (body instanceof String) {
            return objectMapper.writeValueAsString(AjaxResult.success(body));
        }
        //否则直接将对象封装为规定返回格式
        return AjaxResult.success(body);
    }
}
